package com.cqust.wdm.emsboot.service.impl;

import com.cqust.wdm.emsboot.service.IMailService;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.HashMap;
import java.util.Map;

@Service
public class MailServiceImpl implements IMailService {
    @Resource
    private JavaMailSender sender;

    /*
     *  发送简单文本邮件
     * */
    @Override
    public Map<String, Object> send(String subject, String content) {

        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setSubject(subject);
        mailMessage.setText(content);
        mailMessage.setFrom("473065770@qq.com");

        mailMessage.setTo("1679167928@qq.com");
        sender.send(mailMessage);
        Map<String, Object> map = new HashMap<>();
        map.put("success", true);
        return map;
    }

    /*
     * 发送html邮件
     * */
    @Override
    public void sendHtmlMail(String to, String subject, String emailContent) {
        MimeMessage message = sender.createMimeMessage();

        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom("473065770@qq.com");
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(emailContent, true);

            sender.send(message);
            System.out.println("html邮件发送成功");
        } catch (MessagingException e) {
            System.out.println("发送html邮件时发生异常！" + e);
        }
    }
}
